<template>
  <BasicModal @register="registerModal" v-bind="$attrs" wrapClassName="form-modal">
    <template #title>
      <div class="step-form-form">
        <a href="http://glcs.51wit.com/" target="_blank">
          <img src="/src/assets/images/design/logo.png" />
        </a>
        <span>•</span>
        <span>{{ t('表单设计') }} - {{ t('简易模板') }}</span>
        <a-steps :current="current" size="mini">
          <a-step :title="t('基础信息')" />
          <a-step :title="t('表单设计')" />
          <a-step :title="t('表单事件')" />
        </a-steps>
        <div class="btn-box">
          <a-button @click="handleStepPrev" v-show="current !== 0">{{ t('上一步') }}</a-button>
          <a-button type="primary" @click="handleStepNext" v-show="current < 2">
            {{ t('下一步') }}
          </a-button>
          <a-button type="primary" @click="handleSave" v-show="current === 2">
            {{ t('保存') }}
          </a-button>
          <a-button type="primary" danger @click="handleClose">{{ t('关闭') }}</a-button>
        </div>
      </div>
    </template>
    <div class="step-container">
      <BasicConfigStep ref="basicConfigStepRef" v-show="current === 0" />
      <FormDesignStep ref="formDesignStepRef" v-show="current === 1" />
      <FormEventStep ref="formEventStepRef" v-show="current === 2" />
    </div>
  </BasicModal>
  <TableNameModal @register="registerTableName" @success="handleEditSuccess" />
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, toRaw, watch, onMounted } from 'vue';
  import { FormDesignStep, FormEventStep, TableNameModal } from '/@/components/CreateCodeStep';
  import BasicConfigStep from '../BasicConfigStep.vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { GeneratorConfig, CustomFormConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo, upperFieldDb } from '/@/components/Designer';
  import { validateTableName, getMasterInfo } from '/@/api/system/generator';
  import {
    addCodeFirstFormTemplate,
    updateCodeFirstFormTemplate,
    getFormTemplate,
  } from '/@/api/form/design';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import * as antd from '/@/components/Designer/src/types';
  import { random } from 'lodash-es';
  import { noHaveTableAndField } from '/@/components/Designer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';

  const { t } = useI18n();
  const current = ref(0);

  const basicConfigStepRef = ref();
  const formDesignStepRef = ref();
  const formEventStepRef = ref();

  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm))); //FormDesignStep -> designer和StructureConfigStep页面使用
  const mainTableName = ref('table_' + random(10000, 99999));

  const tableInfo = ref<TableInfo[]>([]);
  const isUpdate = ref<boolean>(false);
  const formId = ref<string>('');
  const beforeTableNames = ref<string[]>([]);
  const isFieldUpper = ref<boolean>(false);

  let generatorConfig = reactive<GeneratorConfig>({
    databaseId: 'master',
    formJson: {},
    tableStructureConfigs: [],
    formEventConfig: {},
    isDataAuth: false,
    dataAuthList: [],
  });

  let customFormConfig = reactive<CustomFormConfig>({
    name: '',
    category: '',
    formDesignType: 2,
    formType: FormTypeEnum.CUSTOM_FORM,
    formJson: generatorConfig,
    remark: '',
    isChange: false,
  });

  const [registerTableName, { openModal }] = useModal();

  provide<GeneratorConfig>('generatorConfig', generatorConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<CustomFormConfig>('customFormConfig', customFormConfig);
  provide<Ref<number>>('current', current); //当前步骤
  provide<string>('designType', 'template');
  provide('widgetForm', widgetForm);
  provide<Ref<string>>('mainTableName', mainTableName);
  provide<boolean>('isCustomForm', true); //是自定义表单
  provide<Ref<boolean>>('isFieldUpper', isFieldUpper);

  watch(
    () => generatorConfig,
    (val) => {
      customFormConfig.formJson = val;
    },
    {
      deep: true,
    },
  );
  const emits = defineEmits(['success', 'register', 'close']);

  onMounted(async () => {
    const res = await getMasterInfo();
    isFieldUpper.value = upperFieldDb.includes(res?.dbType || '');
    mainTableName.value = isFieldUpper.value
      ? mainTableName.value.toUpperCase()
      : mainTableName.value;
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    isUpdate.value = !!data.isUpdate;
    formId.value = data.id;
    customFormConfig.isChange = isUpdate.value;
    if (formId.value) {
      getFormTemplateInfo();
    }
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
  });

  async function getFormTemplateInfo() {
    const data = await getFormTemplate(formId.value);
    customFormConfig.name = data.name;
    customFormConfig.category = data.category;
    customFormConfig.formDesignType = data.formDesignType;
    customFormConfig.formJson = JSON.parse(data.formJson);
    customFormConfig.remark = data.remark;

    const { formJson } = customFormConfig;

    generatorConfig.databaseId = formJson.databaseId;
    generatorConfig.isDataAuth = formJson.isDataAuth;
    generatorConfig.dataAuthList = formJson.dataAuthList;
    generatorConfig.tableStructureConfigs = formJson.tableStructureConfigs;
    generatorConfig.formJson = formJson.formJson;
    generatorConfig.formEventConfig = formJson.formEventConfig!;
    generatorConfig.formJson.list = generatorConfig.formJson.list.filter(
      (x) => x.type !== 'hiddenComponent',
    );
    beforeTableNames.value = generatorConfig.tableStructureConfigs?.map((x) => x.tableName) || [];
    getMainTableFirst(generatorConfig.formJson.list);

    widgetForm.value = generatorConfig.formJson;

    basicConfigStepRef.value.setFieldsValue({
      name: customFormConfig?.name,
      category: customFormConfig?.category,
      remark: customFormConfig?.remark,
      databaseId: generatorConfig.databaseId,
      isDataAuth: generatorConfig.isDataAuth,
      dataAuthList: generatorConfig.dataAuthList,
    });
  }

  function getMainTableFirst(list) {
    list.some((x) => {
      if (['tab', 'grid', 'card'].includes(x.type)) {
        for (const child of x.layout!) {
          getMainTableFirst(child.list);
        }
      } else {
        if (x.type !== 'form' && !noHaveTableAndField.includes(x.type)) {
          mainTableName.value = x.bindTable;
          return true;
        }
      }
    });
  }

  function handleClose() {
    closeModal();
    emits('close');
  }

  //上一步
  function handleStepPrev() {
    current.value--;
  }
  //下一步
  async function handleStepNext() {
    const isOk = await stepValidate[current.value]();
    if (!isOk) {
      return;
    }
    current.value++;
  }
  async function handleSave() {
    const isOk = await stepValidate[2]();

    if (!isOk) {
      return;
    }
    const tableNames: string[] = generatorConfig.tableStructureConfigs!.map((x) => x.tableName);

    const testTableNames = tableNames.filter((x) => {
      return !beforeTableNames.value.includes(x);
    });

    if (!isUpdate.value || (isUpdate.value && testTableNames.length)) {
      const names = isUpdate.value ? testTableNames.toString() : tableNames.toString();
      validateName(names);
    } else {
      submitTemplate();
    }
  }

  const validateName = (tableNames) => {
    const params = {
      id: 'master',
      tableNames,
    };
    validateTableName(params, 'none')
      .then(() => {
        submitTemplate();
      })
      .catch((err) => {
        if (!err) return;
        const info = err.message.split('[')[1];
        const existTableName = info.substring(0, info.length - 1).split(',');
        const newTableName: string[] = [];
        generatorConfig?.tableStructureConfigs!.map((table) => {
          const tableName = 'table_' + random(10000, 99999);
          if (existTableName.includes(table.tableName)) {
            table.tableName = tableName;
          }
          newTableName.push(tableName);
          generatorConfig.formJson.list.map((component) => {
            editTableName(component, existTableName, tableName);
          });
        });
        validateName(newTableName.toString());
      });
  };
  const editTableName = (component, existTableName, tableName) => {
    if (existTableName.includes(component.bindTable)) {
      component.bindTable = tableName;
      if (component.children || component.layout || component.list) {
        editTableName(component.children, existTableName, tableName);
      }
    }
  };

  const submitTemplate = async () => {
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }
    if (isUpdate.value) {
      openModal();
    } else {
      await addCodeFirstFormTemplate(toRaw(customFormConfig));
      closeModal();
      emits('success');
      emits('close');
    }
  };

  async function handleEditSuccess() {
    await updateCodeFirstFormTemplate({ id: formId.value, ...toRaw(customFormConfig) });
    closeModal();
    emits('success');
    emits('close');
  }

  const stepValidate = {
    //数据表配置 验证
    0: () => basicConfigStepRef.value.validateStep(),
    1: () => formDesignStepRef.value.validateStep(),
    2: () => formEventStepRef.value.validateStep(),
  };
</script>
<style lang="less" scoped>
  @keyframes rotation {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }
  @keyframes rotationReverse {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(-360deg);
    }
  }

  :deep(.ant-steps-item-process) {
    .ant-steps-item-icon {
      border: 2px solid #fff;
      line-height: 30px;
      animation: rotation 4s linear infinite;
      position: relative;

      &::before {
        border: 2px dashed #1890ff;
        content: '';
        width: 36px;
        height: 36px;
        display: block;
        border-radius: 50%;
        position: absolute;
        left: -4px;
        top: -4px;
      }

      .ant-steps-icon {
        display: inline-block;
        animation: rotationReverse 4s linear infinite;
      }
    }
  }

  .step-form-content {
    padding: 24px;
    background-color: @component-background;
  }

  .step-form-form {
    display: flex;
    align-items: center;
    font-weight: 400;

    a {
      margin-left: -16px;
    }

    span {
      font-size: 16px;
      margin: 0 20px 0 -5px;
      white-space: nowrap;
    }

    :deep(.ant-steps) {
      width: calc(100% - 750px);
    }

    :deep(.ant-steps-item-container) {
      padding: 3px 0 3px 3px;
    }

    .btn-box {
      position: absolute;
      right: 10px;

      :deep(.ant-btn) {
        margin-right: 10px;
      }
    }
  }

  .step-container {
    height: 100%;
  }

  .step1 {
    padding: 0 14px;
    box-sizing: border-box;
  }
</style>
